package com.itic.appbase.framework.utils.configuration;

import java.util.Properties;
import java.util.regex.Matcher;

import com.itic.appbase.framework.utils.StringHelper;

public abstract class PropertiesConfiguration
        implements Configuration {

    static final Properties EMPTY_PROPERTIES = new Properties();
    private static final String EMPTY = "";
    protected Properties properties;

    private String getAndProcessValue(String key) {
        String value = properties.getProperty(key);
        if (StringHelper.isBlank(value)) {
            return EMPTY;
        }
        Matcher matcher = Configuration.VALUE_RESOLVER_PATTERN.matcher(value);
        String resolveKey = null;
        String matchStr = null;
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            matchStr = matcher.group();
            resolveKey = StringHelper.substringBetween(matchStr, "${", "}");
            matcher.appendReplacement(result, properties.getProperty(resolveKey));
        }
        result = matcher.appendTail(result);
        return result.toString();
    }

    @Override
    public String getString(String key) {
        return getAndProcessValue(key);
    }

    @Override
    public boolean getBoolean(String key) {
        String value = getAndProcessValue(key);
        return Boolean.valueOf(value);
    }

    @Override
    public int getInt(String key) {
        String value = getAndProcessValue(key);
        return StringHelper.toInt(value, -1);
    }

    @Override
    public String[] getStringArray(String key) {
        String value = getAndProcessValue(key);
        if (value == null) {
            return new String[0];
        }
        return value.split(",");
    }

    @Override
    public long getLong(String key) {
        String value = getAndProcessValue(key);
        return StringHelper.toLong(value, -1L);
    }

    @Override
    public float getFloat(String key) {
        String value = getAndProcessValue(key);
        if (StringHelper.isBlank(value)) {
            return -1F;
        }
        return Float.parseFloat(value);
    }

    @Override
    public double getDouble(String key) {
        String value = getAndProcessValue(key);
        if (StringHelper.isBlank(value)) {
            return -1D;
        }
        return Double.parseDouble(value);
    }

    @Override
    public boolean containsKey(String key) {
        return properties.containsKey(key);
    }
}
